package com.heima.app.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<String>();
    static {
        urlList.add("/login_auth/");
        urlList.add("/v2/api-docs");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String url : urlList) {
            if (path.contains(url)){
                return chain.filter(exchange);
            }
        }
        try {
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)){
                return writeMessage(exchange,"需要登录");
            }
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i>0){
                return writeMessage(exchange,"认证失效，请重新登录");
            }
            Integer id = claimsBody.get("id",Integer.class);
            request.mutate().header("userId", String.valueOf(id)).build();
            exchange.mutate().request(request);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            return writeMessage(exchange,"认证失效，请重新登录");
        }

    }

    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
